package com.dzsw.netty.ws;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class WebSocketServer {

    public void run(int port) {
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup worker = new NioEventLoopGroup(15);
        ServerBootstrap b = new ServerBootstrap();
        b.group(boss, worker);
        b.channel(NioServerSocketChannel.class);
        b.childHandler(new WebSocketChannelInit());
        try {
            ChannelFuture f = b.bind(port).sync();
            log.info(" server start up on port : " + port);
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        WSConfig.WEBSOCKET_PORT = 8988;
        WSConfig.WEBSOCKET_URL = "ws://localhost:" + WSConfig.WEBSOCKET_PORT;
        new WebSocketServer().run(WSConfig.WEBSOCKET_PORT);
    }
}
